/****************************************************
文件：AreaRandomGenerate.cs
作者：UnitySir
邮箱：zouajck@foxmail.com
日期：2021/03/22 09:53:33
功能：Nothing
*****************************************************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AreaRandomGenerate : MonoBehaviour
{
    [Header("生成物体的最大数量")] [SerializeField] private int objNumMax = 12;

    public int ObjNumMax
    {
        get { return objNumMax; }
        set { objNumMax = value; }
    }

    [Header("当前物体的数量")] [SerializeField] private int objCurrNum = 0;

    [Header("需要加载的物体对象")] [SerializeField] private GameObject objPrefabObj;
    [Header("物体列表")] [SerializeField] private List<GameObject> objList = new List<GameObject>();

    [Header("生成物体的时间间隔")] [SerializeField] [Range(1, 60)]
    private float generateTime;

    [Header("生成物体的偏移量")] [SerializeField] private Vector3 offset = Vector3.zero;

    [Header("生成物体的父对象")] [SerializeField] private Transform parent = null;

    private string objName;

    public string ObjName
    {
        get { return objName; }
        set { objName = value; }
    }

    /// <summary>
    /// 利用协程生成怪物
    /// </summary>
    /// <returns></returns>
    public IEnumerator Generate()
    {
        while (true)
        {
            if (objCurrNum < objNumMax)
            {
                //随机生成一个本地坐标
                var localPos = new Vector3(GetRndF(), GetRndF(), GetRndF()) + offset;
                //将本地坐标转为世界坐标,TransformPoint()会根据当前对象的坐标和缩放来转换
                var pos = transform.TransformPoint(localPos);
                //获取随机的方向
                //var rotation = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f);
                //实例化一个对象
                var objInstance = Instantiate(objPrefabObj, pos, Quaternion.Euler(Vector3.zero), parent);
                objInstance.name = objName;
                objList.Add(objInstance);
                objCurrNum++;

                yield return new WaitForSeconds(generateTime); //每隔generateTime秒
            }

            yield return null;
        }
    }

    /// <summary>
    /// 获取随机数
    /// </summary>
    /// <returns></returns>
    private float GetRndF()
    {
        return Random.Range(-0.5f, 0.5f);
    }
}